package com.xinchuang.service.actual.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinchuang.comment.KeyWord;
import com.xinchuang.comment.R;
import com.xinchuang.domain.entity.DictTable;
import com.xinchuang.domain.entity.TestRecordMainTable;
import com.xinchuang.domain.entity.TestRecordProblemTable;
import com.xinchuang.domain.pojo.TestStatisticsTable;
import com.xinchuang.mapper.*;
import com.xinchuang.service.OaUserService;
import com.xinchuang.service.actual.CloseQuestionService;
import com.xinchuang.utils.MyUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * TODO
 *
 * @author zkwczx
 * @version 1.0
 * @date 2023/7/5 19:43
 */
@Service
@RequiredArgsConstructor
public class CloseQuestionServiceImpl implements CloseQuestionService {

    private final TestNoticeTimeTableMapper timeTableMapper;

    private final TestRecordMainTableMapper recordMainTableMapper;

    private final TestRecordProblemTableMapper problemTableMapper;

    private final TestStatisticsTableMapper statisticsTableMapper;

    private final DictTableMapper dictTableMapper;

    private final KeyWord keyWord;

    private final OaUserService oaUserService;

    @Override
    public String tryOutColsedQuestion(JSONObject jsonObject) {
        //jsonobject解析获取模具工号
        String moldId = jsonObject.getString("moldId");
        TestRecordMainTable recordMainTable = recordMainTableMapper.selectOne(
                new QueryWrapper<TestRecordMainTable>()
                        .lambda()
                        .eq(TestRecordMainTable::getMoldId, moldId)
                        .orderByDesc(TestRecordMainTable::getCreateTime)
                        .last("LIMIT 1")
        );
        JSONObject json = new JSONObject();
        //头
        json.put("projectName", ObjectUtil.isNull(recordMainTable) || StringUtils.isBlank(recordMainTable.getProjectName()) ? "" : recordMainTable.getProjectName());
        json.put("moldName", ObjectUtil.isNull(recordMainTable) || StringUtils.isBlank(recordMainTable.getProductName()) ? "" : recordMainTable.getProductName());
        json.put("moldId", ObjectUtil.isNull(recordMainTable) || StringUtils.isBlank(recordMainTable.getMoldId()) ? "" : recordMainTable.getMoldId());
        json.put("moldMaterial", ObjectUtil.isNull(recordMainTable) || StringUtils.isBlank(recordMainTable.getProductMaterial()) ? "" : recordMainTable.getProductMaterial());
        json.put("moldWeight", ObjectUtil.isNull(recordMainTable) || StringUtils.isBlank(recordMainTable.getProductWeight()) ? "" : recordMainTable.getProductWeight());
        json.put("mainEnginePlantId", ObjectUtil.isNull(recordMainTable) || StringUtils.isBlank(recordMainTable.getHostFactory()) ? "" : recordMainTable.getHostFactory());
        json.put("projectManager", oaUserService.getOaUserName(recordMainTable.getProjectManager()));
        json.put("moldDesigner", oaUserService.getOaUserName(recordMainTable.getDesignerUserId()));
        json.put("tongmanName", oaUserService.getOaUserName(recordMainTable.getTongmanName()));
        json.put("surfaceRequire", ObjectUtil.isNull(recordMainTable) || StringUtils.isBlank(recordMainTable.getSurfaceRequirements()) ? "" : recordMainTable.getSurfaceRequirements());
        json.put("partsStorageBin", ObjectUtil.isNull(recordMainTable) || StringUtils.isBlank(recordMainTable.getPartFactory()) ? "" : recordMainTable.getPartFactory());
        json.put("tryOutTime", ObjectUtil.isNull(recordMainTable) || StringUtils.isBlank(recordMainTable.getToTime()) ? "" : recordMainTable.getToTime());
        if (ObjectUtil.isNotNull(recordMainTable)) {
            JSONArray array = tryOutColsedQuestionStageData(recordMainTable);
            json.put("stageData", array);
        } else {
            json.put("stageData", new JSONArray());
        }
        return JSON.toJSONString(R.data(json));
    }

    //试模阶段列表
    @Override
    public JSONArray tryOutColsedQuestionStageData(TestRecordMainTable recordMainTable) {
        //试模阶段
        JSONArray array = new JSONArray();
        JSONObject data;
        int totalCount = 0;
        int actualCount = 0;
        int issuesTotal = 0;
        for (int i = 0; i <= 20; i++) {
            data = new JSONObject();
            List<TestRecordProblemTable> problemTable = problemTableMapper.selectList(
                    new LambdaQueryWrapper<TestRecordProblemTable>()
                            .eq(TestRecordProblemTable::getParentRecordId, recordMainTable.getId())
                            .eq(TestRecordProblemTable::getPhase, "T" + i)
            );
            data.put("stageName", "T" + i);
            data.put("reason", "");
            data.put("plannedTime", "");
            data.put("realTime", "");
            data.put("raisedCount", "");
            data.put("totalCount", "");
            data.put("plannedDoneCount", "");
            data.put("closedCount", "");
            data.put("needToChangeCount", "");
            data.put("stageCloseRate", "");
            data.put("totalCloseRate", "");
            if (CollectionUtil.isNotEmpty(problemTable)) {
                int plan = 0;
                int actual = 0;
                int onlyAdd = 0;
                for (TestRecordProblemTable table : problemTable) {
                    if (StringUtils.isNumeric(table.getIssuesTotal())) {
                        onlyAdd += Integer.valueOf(table.getIssuesTotal());
                        issuesTotal += Integer.valueOf(table.getIssuesTotal());
                        totalCount += Integer.valueOf(table.getIssuesTotal());
                    }
                    Map<String, Integer> resumeAll = timeTableMapper.getResumeAll(table.getProblemId());
                    if (ObjectUtil.isNotNull(resumeAll)) {
                        plan += resumeAll.get("plan");
                        actual += resumeAll.get("actual");
                        actualCount += resumeAll.get("actual");
                    }
                }
                Map<String, Object> modelStage = timeTableMapper.getModelStage(
                        recordMainTable.getMoldId(),
                        i + ""
                );
                if (ObjectUtil.isNotNull(modelStage)) {
                    data.put("reason", ObjectUtil.isNull(modelStage.get("sub_target")) ? "" : modelStage.get("sub_target"));
                    data.put("plannedTime", ObjectUtil.isNull(modelStage.get("planned_time")) ? "" : modelStage.get("planned_time"));
                    data.put("realTime", ObjectUtil.isNull(modelStage.get("practical_time")) ? "" : modelStage.get("practical_time"));
                }
                data.put("raisedCount", onlyAdd);
                data.put("totalCount", issuesTotal);
                data.put("plannedDoneCount", plan);
                data.put("closedCount", actual);
                int nowIssuesTotal = totalCount - actualCount;
                if (nowIssuesTotal < 0) {
                    nowIssuesTotal = 0;
                }
                data.put("needToChangeCount", nowIssuesTotal);
                data.put("stageCloseRate", actual > 0 && plan > 0 ? MyUtils.formatDouble(actual / (double) plan * 100) : 0);
                data.put("totalCloseRate", nowIssuesTotal > 0 && issuesTotal > 0 ? MyUtils.formatDouble((1 - nowIssuesTotal / (double) issuesTotal) * 100) : 0);
            }
            array.add(data);
        }
        return array;
    }

    @Override
    public String addTryOutColsedQuestion(JSONObject jsonObject) {
        //jsonobject解析获取模具工号
        String moldId = jsonObject.getString("moldId");
        //jsonobject解析获取试模阶段数据
        JSONArray stageData = jsonObject.getJSONArray("stageData");
        TestRecordMainTable recordMainTable = recordMainTableMapper.selectOne(new QueryWrapper<TestRecordMainTable>()
                .lambda()
                .eq(TestRecordMainTable::getMoldId, moldId));
        if (ObjectUtil.isNotNull(recordMainTable)) {
            if (CollectionUtil.isNotEmpty(stageData)) {
                statisticsTableMapper.delete(new QueryWrapper<TestStatisticsTable>()
                        .lambda()
                        .eq(TestStatisticsTable::getParentRecordId, recordMainTable.getId()));
                for (Object stageDatum : stageData) {
                    LinkedHashMap data = (LinkedHashMap) stageDatum;
                    TestStatisticsTable statisticsTable = new TestStatisticsTable();
                    statisticsTable.setParentRecordId(recordMainTable.getId());
                    statisticsTable.setTestStage(data.get("stageName").toString());
                    statisticsTable.setTestCauses(data.get("reason").toString());
                    statisticsTable.setPlanTime(data.get("plannedTime").toString());
                    statisticsTable.setActualTime(data.get("realTime").toString());
                    statisticsTable.setNewIssues(data.get("raisedCount").toString());
                    statisticsTable.setIssuesTotal(data.get("totalCount").toString());
                    statisticsTable.setSolvedIssues(data.get("plannedDoneCount").toString());
                    statisticsTable.setClosedIssues(data.get("closedCount").toString());
                    statisticsTable.setModifiedIssues(data.get("needToChangeCount").toString());
                    statisticsTable.setStage(data.get("stageCloseRate").toString());
                    statisticsTable.setTotal(data.get("totalCloseRate").toString());
                    statisticsTableMapper.insert(statisticsTable);
                }
                return JSON.toJSONString(R.success("保存成功"));
            }
        }
        return JSON.toJSONString(R.success("无数据"));
    }

    @Override
    public String imageUpload(MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            return JSON.toJSONString(R.fail("请选择文件上传"));
        }
        String fileName = file.getOriginalFilename();
        // 文件存储根路径
        String rootUrl = keyWord.getFileUrl();
        File rootPath = FileUtil.newFile(rootUrl);
        if (!rootPath.exists()) {
            FileUtil.mkdir(rootPath);
        }
        String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String middle = "file/" + date + "/";
        String iconUrl = middle + fileName;
        try {
            FileUtil.touch(rootUrl + "/" + iconUrl);
            FileUtil.writeBytes(file.getBytes(), rootUrl + "/" + iconUrl);
        } catch (IOException e) {
            FileUtil.del(rootUrl + "/" + iconUrl);
            return JSON.toJSONString(R.fail("上传出现错误，请重试"));
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("createTime", new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
        resultMap.put("filePath", iconUrl);
        resultMap.put("fileName", fileName);
        return JSON.toJSONString(R.data(resultMap, "上传成功"));
    }

}
